import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:tracker/common/model/base_resp.dart';
import 'package:tracker/pages/home/home/model/device_base_info_resp.dart';
import 'package:tracker/pages/home/home/model/home_device_info_resp.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/theme/app_theme.dart';
import 'package:tracker/utils/toast_utils.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../../../common/enums/user_type_enum.dart';

class DeviceInfoPage extends ConsumerStatefulWidget {
  const DeviceInfoPage({super.key});

  @override
  ConsumerState<DeviceInfoPage> createState() => _DeviceInfoPageState();
}

class _DeviceInfoPageState extends ConsumerState<DeviceInfoPage> {
  DeviceBaseInfoData baseInfoData = DeviceBaseInfoData();
  final _deviceNameController = TextEditingController();
  String _addressString = '';
  _buildList() {
    double descFontSize = 16;
    return Padding(
      padding: EdgeInsets.only(left: 8, right: 8, top: 20),
      child: Column(
        children: [
          Container(
          //   // padding: EdgeInsets.only(left: 8, right: 8, top: 20),
          //   decoration: BoxDecoration(
          //     color: Color(0xFFEEEEEF),
          //     borderRadius: BorderRadius.circular(6),
          //   ),
          //   child: ListView.separated(
          //     itemCount: 5,
          //
          //     shrinkWrap: true,
          //     itemBuilder: (context, index) {
          //       switch (index) {
          //         case 0:
          //
          //         case 1:
          //           return _buildTableCell('设备号', baseInfoData.imei ?? '');
          //         case 2:
          //           return _buildTableCell('设备型号', baseInfoData.model ?? '');
          //         case 3:
          //           return _buildTableCell('到期时间', baseInfoData.expiryTime ?? '');
          //         case 4:
          //           return Divider(color: Color(0xFFFFFFFF),thickness: 10,);
          //       }
          //     },
          //     separatorBuilder: (context, index) {
          //       return Container();
          //     },
          //   ),
            decoration: BoxDecoration(
              color: Color(0xFFEEEEEF),
              borderRadius: BorderRadius.circular(6),
            ),
            child: Column(

              children: [
                _biuldOneRow(),
               _buildTableCell('设备名称', baseInfoData.deviceName ?? ''),
               _buildTableCell('设备账号', baseInfoData.imei ?? ''),
               _buildTableCell('设备型号', baseInfoData.model ?? ''),
               // _buildTableCell('手机号', baseInfoData.imei ?? ''),

              ],
            ),
          ),
          SizedBox(height: 10,),
          Container(
            // padding: EdgeInsets.only(left: 8, right: 8, top: 20),
            decoration: BoxDecoration(
              color: Color(0xFFEEEEEF),
              borderRadius: BorderRadius.circular(6),
            ),
            child: Column(
              children: [
                _buildTableCell('ICCID号', baseInfoData.iccid ?? ''),
                // _buildTableCell('经纬度：', baseInfoData.deviceName ?? ''),
                _buildTableCell('到期时间：', baseInfoData.expiryTime ?? '')
                ],
            ),
          ),
          SizedBox(height: 10,),

          Container(
            // padding: EdgeInsets.only(left: 8, right: 8, top: 20),
            decoration: BoxDecoration(
              color: Color(0xFFEEEEEF),
              borderRadius: BorderRadius.circular(6),
            ),
            child: Column(
              children: [
                _buildTableCell('绑定手机号：', _phoneNumber()),
                _buildTableCell('地址：', _addressString),
              ],
            ),
          ),
        ],
      )
    );
  }

  Widget _biuldOneRow() {
    return GestureDetector(
                    onTap: () {
                      // 弹窗输入新的设备名称
                      showDialog(
                          context: context,
                          builder: (context) {
                            return AlertDialog(
                              backgroundColor: Colors.white,
                              surfaceTintColor: Colors.white,
                              title: Text('修改设备名称'),
                              content: TextField(
                                controller: _deviceNameController,
                                decoration: InputDecoration(
                                  hintText: '请输入新的设备名称',
                                  // 下划线颜色
                                  focusedBorder: UnderlineInputBorder(
                                    borderSide: BorderSide(
                                      color: AppTheme.themeConfig.primaryColor,
                                    ),
                                  ),
                                ),
                                // 光标颜色
                                cursorColor: AppTheme.themeConfig.primaryColor,
                                // 长度限制
                                maxLength: 16,
                              ),
                              actions: [
                                TextButton(
                                  onPressed: () {
                                    Navigator.of(context).pop();
                                  },
                                  child: Text(
                                    '取消',
                                    style: TextStyle(
                                        color: AppTheme.themeConfig.primaryColor),
                                  ),
                                ),
                                TextButton(
                                  onPressed: () {
                                    _modifyDeviceName();
                                  },
                                  child: Text(
                                    '确定',
                                    style: TextStyle(
                                        color: AppTheme.themeConfig.primaryColor,
                                        fontWeight: FontWeight.bold),
                                  ),
                                ),
                              ],
                            );
                          });
                    },
                    child: _buildTableCell('设备名称', baseInfoData.deviceName ?? '',
                        showArrow: true),
                  );
  }
  Future<void> loadaddressString() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _addressString = prefs.getString('monitorDataAddress')?? "";
    });
  }
  String _phoneNumber() {
    final userType = ref.watch(userTypeProvider);
    final userInfo = ref.watch(userInfoProvider);
    if (userType == UserTypeEnum.phone) {
      return userInfo.phone ?? '';
    }
    return "暂无";
  }
  _buildTableCell(String title, String desc, {bool showArrow = false}) {
    return Container(
        constraints: BoxConstraints(minHeight: 40),
        padding: EdgeInsets.only(left: 20, right: 15, top: 12, bottom: 12),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(26.0),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              title,
              style: TextStyle(fontSize: 16),
            ),
            Row(
              children: [Container(
                // color: Colors.blue,
                width: ScreenUtil.getScreenW(context) - 150,
                alignment: Alignment.centerRight,
                child: Text(
                  desc,
                  textAlign: TextAlign.right,
                  style: TextStyle(
                      fontSize: 16,
                      // color: AppTheme.themeConfig.infoTextColor,
                      fontWeight: FontWeight.normal),
                  // overflow: TextOverflow.ellipsis,
                ),
              ),

                if (showArrow)
                  Icon(
                    Icons.arrow_forward_ios,
                    size: 16,
                    color: AppTheme.themeConfig.infoTextColor,
                  ),
              ],
            ),
          ],
        ));
  }

  void _fetchDeviceInfo() async {
    DeviceInfoVO deviceInfo = ref.watch(deviceInfoProvider);
    var res = await get<DeviceBaseInfoResp, DeviceBaseInfoResp>(
        '/device/base/${deviceInfo.imei}',
        decodeType: DeviceBaseInfoResp());
    res.when(
        success: (resp) {
          if (resp.code == 200) {
            setState(() {
              baseInfoData = resp.data!;
            });
          } else {
            ToastUtils.showToast(resp.msg ?? '未查询到设备信息');
          }
        },
        failure: (String msg, int code) {});
  }

  void _modifyDeviceName() async {
    // 校验设备名称，不能为空
    if (_deviceNameController.text.isEmpty) {
      ToastUtils.showToast('设备名称不能为空');
      return;
    }
    var postData = {
      'imei': baseInfoData.imei,
      'deviceName': _deviceNameController.text,
    };
    ToastUtils.showLoading();
    var res = await post<BaseResp, BaseResp>('/device/updateName',
        data: postData, decodeType: BaseResp());
    res.when(
        success: (resp) {
          ToastUtils.dismissLoading();
          if (resp.code == 200) {
            ToastUtils.showToast('修改成功');
            Navigator.of(context).pop();
            _fetchDeviceInfo();
          } else {
            ToastUtils.showToast(resp.msg ?? '修改失败');
          }
        },
        failure: (String msg, int code) {});
  }

  @override
  void initState() {
    //监听Widget是否绘制完毕
    WidgetsBinding.instance.addPostFrameCallback(_afterLayout);
    super.initState();
    loadaddressString();

  }

  @override
  void dispose() {
    super.dispose();
  }

  _afterLayout(_) {
    _fetchDeviceInfo();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('设备信息'),
        centerTitle: true,
        backgroundColor: AppTheme.themeConfig.navBarColor,
        foregroundColor: Colors.white,
        leading: GestureDetector(
          onTap: () {
            Navigator.pop(context);
          },
          child: Container(
            height: kToolbarHeight,
            padding: const EdgeInsets.only(top: 8),
            alignment: Alignment.center,
            child: const Text(' <返回',
                textAlign: TextAlign.center,
                maxLines: 1,
                style: TextStyle(color: Colors.black)),
          ),

        ),
      ),
      backgroundColor: Color(0xFFFFFFFF),
      body: _buildList(),
    );
  }
}
